package org.groupg.practice;

import org.jgroups.*;
import org.jgroups.blocks.MessageDispatcher;

import org.jgroups.blocks.RequestHandler;
import org.jgroups.blocks.RequestOptions;
import org.jgroups.blocks.ResponseMode;

public class MessageListenerExample implements Receiver, RequestHandler {
    private JChannel channel;
    private MessageDispatcher disp;

    public static void main(String[] args) throws Exception {
        new MessageListenerExample().start();
    }

    private void start() throws Exception {
        channel = new JChannel();
        disp = new MessageDispatcher(channel, this);
        channel.connect("MessageListenerCluster");

        // 发送广播消息
        for (int i = 0; i < 5; i++) {
            String msg = "Message " + i;
            System.out.println("Sending: " + msg);
            disp.castMessage(null, new ObjectMessage(null, msg),
                    RequestOptions.SYNC().setMode(ResponseMode.GET_NONE));
            Thread.sleep(3000);
        }

        channel.close();
    }

    @Override
    public void receive(Message msg) {
        System.out.println("Received: " + msg.getObject());
    }

    @Override
    public Object handle(Message msg) throws Exception {
        System.out.println("Handling request: " + msg.getObject());
        return "Response to: " + msg.getObject();
    }
}